import { terminal, closeType, cardType, routeType, chooseImageSizeType, chooseImageSourceType } from '@/config/const.js'
import showModal from '@/utils/showModalHandler.js'
import cacheHandler from '@/utils/cacheHandler'
// #ifdef H5
import wechat from '@/utils/wechat'
// #endif

// 身份证校验
function IdentityCodeValid(card) {
  let pass = true
  let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (reg.test(card) === false) {
    pass = false
  }
  return pass
}

// 手机号校验
function checkMobile(str) {
  let pass = true
  let reg = /^1[3456789]\d{9}$/
  if (reg.test(str) === false) {
    pass = false
  }
  return pass
}

// 根据身份证获取性别和出生年月
function analyzeIDCard(idCard) {
  let sexIndex = ''
  if (parseInt(idCard.substr(16, 1)) % 2 === 1) {
    sexIndex = '0'
  } else {
    sexIndex = '1'
  }
  const yearBirth = idCard.substring(6, 10)
  const monthBirth = idCard.substring(10, 12)
  const dayBirth = idCard.substring(12, 14)
  const birthDate = yearBirth + '-' + monthBirth + '-' + dayBirth
  return [sexIndex, birthDate]
}

// 计算两个时间点的日期数组含星期
function getDayArray(start, end) {
  return new Promise (function(resolve, reject) {
    const startDate = handleDayArrayData(start).split('-')
    const endDate = handleDayArrayData(end).split('-')
    let dayDateList = []
    for (let i = start; i <= end; i++) {
      dayDateList.push(handleDayArrayData(i).split('-'))
    }
    resolve({ startDate: startDate, endDate: endDate, dayDateList: dayDateList })
  })
}

// 获取当前几天后的日期并添加星期字符串
function handleDayArrayData(day) {
  const weekList = ['日', '一', '二', '三', '四', '五', '六']
  let currentDate = new Date()
  currentDate.setTime(currentDate.getTime() + 1000 * 60 * 60 * 24 * day)
  const targetDateYear = currentDate.getFullYear()
  let targetDateMonth = currentDate.getMonth() + 1
  targetDateMonth = targetDateMonth < 10 ? '0' + targetDateMonth : targetDateMonth
  let targetDateDay = currentDate.getDate()
  targetDateDay = targetDateDay < 10 ? '0' + targetDateDay : targetDateDay
  const targetDateWeek = '星期' + weekList[currentDate.getDay()]
  return targetDateYear + '-' + targetDateMonth + '-' + targetDateDay + '-' + targetDateWeek
}

// 格式转换日期 yyyy－mm－dd
function formatDate(date) {
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return year + '-' + month + '-' + day
}

// 计算日期加多少天后的日期
function addDays(date, days) {
  let result = new Date(date)
  result.setDate(result.getDate() + days)
  return result
}

// 选择图片
function chooseImage(count = 1, sizeType = [chooseImageSizeType.ORIGINAL, chooseImageSizeType.COMPRESSED], sourceType = [chooseImageSourceType.ALBUM, chooseImageSourceType.CAMERA]) {
  return new Promise(function(resolve, reject) {
    uni.chooseImage({
      count: count, // 上传张数最多9张
      sizeType: sizeType, // original 原图，compressed 压缩图，默认二者都有
      sourceType: sourceType, // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        resolve(res)
      },
      fail: function(err) {
        reject(err)
      }
    })
  })
}

/**
 * 打开链接文件
 */
function protogenesisOpenPdf(url, fileType = 'pdf') {
  return new Promise(function(resolve, reject) {
    uni.showLoading({
      title: '正在加载'
    })
    uni.downloadFile({
      url: url,
      success: function(res) {
        var filePath = res.tempFilePath
        uni.openDocument({
          filePath: filePath,
          fileType: fileType,
          success: function(res) {
            uni.hideLoading()
            console.log('文件打开成功')
            resolve(res)
          },
          fail: function(err) {
            console.log('文件打开失败', err)
            showModal.showConfirmModal(err)
            uni.hideLoading()
            reject(err)
          }
        })
      },
      fail: function(err) {
        console.log('文件下载失败', err)
        showModal.showConfirmModal(err)
        uni.hideLoading()
        reject(err)
      }
    })
  })
}

/**
 * 查看电子链接文件(适配)---有待完善
 */
function viewElectronicFiles(fileUrl) {
  const systemInfo = cacheHandler.getSystemInfo()
  switch (systemInfo.platform) {
    case 'android':
      // 安卓调用原生的方法
      protogenesisOpenPdf(fileUrl)
      break
    case 'ios':
      protogenesisOpenPdf(fileUrl)
      // ios跳转web-view页面
      // uni.navigateTo({
      //   url: "/page/web-view/web-view?url=" + fileUrl
      // })
      break
    default:
      protogenesisOpenPdf(fileUrl)
      break
  }
}

/**
 * 获取位置信息(适配)---有待完善
 */
function getLocation() {
  return new Promise(function(resolve, reject) {
    const terminalId = cacheHandler.getTerminalId()
    if (terminalId === terminal.WX_CLIENT) {
      // 微信公众号适配
      wechat.getLocation().then((res) => {
        console.log('获取位置信息res', res)
        resolve(res)
      }).catch((err) => {
        console.log('获取位置信息err', err)
        reject(err)
      })
    } else {
      // 通常情况
      uni.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标
        // geocode: true, // 默认false，是否解析地址信息
        isHighAccuracy: true, // 开启高精度定位
        success: (res) => {
          console.log('获取位置信息res', res)
          resolve(res)
        },
        fail: (err) => {
          console.log('获取位置信息err', err)
          reject(err.errMsg)
        }
      })
    }
  })
}

/**
 * 订阅消息判断 type模板类型，flag禁行标志
 * resolve(code) code=1执行后续方法，code=2弹出订阅消息指导蒙板，code=3禁止执行后续方法并提醒
 */
function subscribeMessageJudgment(type, flag = false) {
  return new Promise(function(resolve, reject) {
    const terminalId = cacheHandler.getTerminalId()
    if (terminalId === terminal.WX_MINI_CLIENT) {
      const templIds = cacheHandler.getMsgTemplateId()[type]
      wx.requestSubscribeMessage({
        tmplIds: templIds,
        complete(res) {
          if (res.errMsg !== 'requestSubscribeMessage:fail last call has not ended') {
            let allAccept = true
            if (templIds) {
              templIds.forEach((item) => {
                if (res[item] !== 'accept') {
                  allAccept = false
                  if (flag) {
                    resolve(3)
                  } else {
                    resolve(2)
                  }
                }
              })
              if (allAccept) {
                resolve(1)
              }
            } else {
              if (flag) {
                resolve(3)
              } else {
                resolve(1)
              }
            }
          }
        }
      })
    } else if (terminalId === terminal.ZFB_MINI_CLIENT) {
      // 支付宝订阅---待完善
      resolve(1)
    } else {
      resolve(1)
    }
  })
}

/**
 * 获取服务供应商
 */
function getProvider(serviceType) {
  // 授权情况返回:[weixin]、[alipay],支付情况返回:[wxpay]、[alipay]，h5都为[]
  return new Promise(function(resolve, reject) {
    uni.getProvider({
      service: serviceType, // 授权:oauth，支付:payment，const中定义
      success: function(res) {
        resolve(res)
      },
      fail: function(err) {
        reject(err.errMsg)
      }
    })
  })
}

/**
 * 配置平台首页和个人中心功能跳转管理
 */
function routeHandler(config) {
  if (config.close === closeType.CLOSE) {
    showModal.showToast(config.closeReason)
    return
  }
  let patInfo = cacheHandler.getDefaultPatInfo()
  if (config.isCard === cardType.HAS_CARD && !patInfo.reg_no) {
	  showModal.showModal('使用此功能需先绑定就诊卡，是否去绑定？').then(res => {
	    if (res.confirm) {
	      uni.navigateTo({
	        url: '/pages/card-patient/card-patient-list/index'
	      })
	    }
	  })
    return
  }
  switch (config.buttonType) {
    case routeType.NAVIGATE:
      uni.navigateTo({
        url: config.url
      })
      break
    case routeType.REDIRECT:
      uni.redirectTo({
        url: config.url
      })
      break
    case routeType.SWITCHTAB:
      uni.switchTab({
        url: config.url
      })
      break
    case routeType.RELAUNCH:
      uni.reLaunch({
        url: config.url
      })
      break
    default:
      break
  }
}

/**
 * 判断当前浏览器是否为微信
 */
function isWeChatBrowser(userAgent) {
  return /micromessenger/.test(userAgent.toLowerCase())
}

/**
 * 判断当前浏览器是否为支付宝
 */
function isAlipayBrowser(userAgent) {
  return /alipayclient/.test(userAgent.toLowerCase())
}

/**
 * 防抖：一段时间内只触发最后一次，重复触发会重置计时器
 */
function debounce(func, wait = 1500) {
  let timeout = null
  return function() {
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      func.apply(this, arguments)
    }, wait)
  }
}

/**
 * 节流：先触发一次，单位时间内只触发一次
 */
const throttle = function throttle(func, wait = 1500) {
  let lastTime = null
  // 返回新的函数
  return function() {
    let nowTime = +new Date() // 获取当前时间戳
    if (!lastTime || nowTime - lastTime > wait) {
      lastTime = nowTime
      func.apply(this, arguments) // 将this和参数传给原函数
    }
  }
}

/**
 * 占位符替换
 */
function regexReplace(str) {
  if (!str) {
    return null
  }
  if (arguments.length === 1) return str
  for (var i = 1; i < arguments.length + 1; i++)
    str = str.replace(new RegExp('\\{' + i + '\\}', 'g'), arguments[i])
  return str
}

export default {
  IdentityCodeValid,
  checkMobile,
  analyzeIDCard,
  getDayArray,
  handleDayArrayData,
  formatDate,
  addDays,
  chooseImage,
  protogenesisOpenPdf,
  viewElectronicFiles,
  getLocation,
  subscribeMessageJudgment,
  getProvider,
  routeHandler,
  isWeChatBrowser,
  isAlipayBrowser,
  debounce,
  throttle,
  regexReplace
}
